import time

import numpy as np
import pandas as pd


input_example = ['test', 'pre', 'process']
output_example = []


def compare(o_e, o):
    if o_e == None and o == []:
        return True
    if o_e == o:
        return True
    else:
        return False


def select_node(filepath, choice):
    file = open(filepath)
    lines = file.readlines()
    file.close()
    if not lines:
        return
    ips = []
    for i in range(len(lines)):
        if choice[i] == 1:
            ips.append(lines[i])
    return ips


def read_data(filepath):
    with open(filepath, "r") as f:
        lines = f.readlines()
        for line in lines:
            line = line.rstrip("\n")
        return lines


vm_attr_path = "./names/names_vm.txt"
# vm_attr_path = "/collector_slave/config/names/names_vm.txt"
vm_ip_path = "/collector_slave/config/ips/ips_slave.conf"
pod_attr_path = "/collector_slave/config/names/names_container.txt"
pod_ip_path = "/collector_slave/config/ips/ips_slave.conf"


def vm_data_to_array(resp, choice):
    ips = ['172.28.2.197', '172.28.2.198', '172.28.2.199', '172.28.2.200']
    temp_dict = {'a': {'b': 1}}
    for data in resp:
        es = data.split(":")
        if len(es) == 5:
            if es[2] in ips:
                add_2d_dict(temp_dict, es[2], es[0], es[4])
    attrs = read_data(vm_attr_path)
    result = [[0 for i in range(len(attrs))] for i in range(len(ips))]

    i = 0
    flag = False
    for ip in ips:
        ip = ip.rstrip("\n")
        j = 0
        for attr in attrs:
            attr = attr.rstrip("\n")
            if ip in temp_dict:
                flag = True
                if attr in temp_dict[ip]:
                    result[i][j] = float(temp_dict[ip][attr])
                else:
                    result[i][j] = float('nan')
            j = j + 1
        i = i + 1
    if flag:
        return result
    else:
        return None


def array_to_vm_data(resp, t):
    ips = ['172.28.2.197', '172.28.2.198', '172.28.2.199', '172.28.2.200']
    attrs = read_data(vm_attr_path)
    result = []
    i = 0
    if resp:
        for unit in resp:
            j = 0
            for v in unit:
                # string = ips[i].rstrip("\n") + " " + attrs[j].rstrip("\n") + " " + str(round(v, 6))
                string = attrs[j].rstrip("\n") + ":vm:" + ips[i].rstrip("\n") + ":" + t + ":" + str(round(float(v), 6))
                result.append(string)
                j = j + 1
            i = i + 1
        return result


def add_2d_dict(d, k_a, k_b, v):
    assert isinstance(d, dict)
    if k_a in d:
        d[k_a].update({k_b: v})
    else:
        d.update({k_a: {k_b: v}})


def float2str(arr):
    res = []
    for i in 4:
        ta=[]
        for j in range(21):
            ta.append(str(round(arr[i][j],6)))
#        temp_arr[i][j]=str(temp_arr[i][j])
        arr.append(ta)
    return arr


def get_ms_time():
    t = time.time()
    return str(round(t * 1000))


def ourpreprocess(temp_arr):
    if temp_arr:
        no=temp_arr.shape[1]
        DSIZE=temp_arr.shape[0]
        for num in range(0,no):
            value=temp_arr[:,num]
            npArray=dataPreprocess(value,DSIZE)
            temp_arr[:, num]=npArray
        return temp_arr

def dataPreprocess(npArray,DSIZE):
    missingValue=pd.notna(npArray)
    print(missingValue)

    # 存在缺失值，进行缺失值填充
    if(pd.isna(npArray).sum()>0):
        # 进行缺失值填充
        npArray[np.isnan(npArray)]=0.0

    # 百分比离群点检测
    npArray=percent_range(npArray,DSIZE, 0.025, 0.975)
    return npArray


# 百分位法:原始参数 min=0.025， max=0.975
def percent_range(dataset,DSIZE, min=0.20, max=0.80):
    range_max = np.percentile(dataset, max * 100)
    range_min = -np.percentile(-dataset, (1 - min) * 100)

    result=np.empty((DSIZE,))
    i=0
    for value in dataset:
        if value <= range_max and value >= range_min:
            result[i]=dataset[i]
        else:
            result[i]=-1

        i+=1
    return result


# 用例目的
print("该用例目的为：")
print("进行预处理系统整体测试，测试处理系统在错误输入下的表现")

# 子用例编号
print("子用例编号：")
print("Ourpreprocess_5")

print("****************************")
print("当前输入为：")
# 输出用例设置
print(input_example)
# 输出用例设置

print("")

print("****************************")
print("当前输出为:")
# 输出处理后数据
t = time.time()
temp = vm_data_to_array(input_example, [1])
temp = ourpreprocess(np.array(temp))
output = array_to_vm_data(temp, get_ms_time())
print(output)
cost = time.time() - t
# 输出处理后数据

print("****************************")
print("是否正确:")
# 输出对比结果
# 需要写一个compare函数
if compare(output, output_example):
    print("输出与预定目标相符")
    print(f"用时：{cost}")
else:
    print("输出与预定目标不符")
# 输出对比结果

print("\n")
